package com.longrise.android.byjk.plugins.dealsituation.cachecourse;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.common.FolderConstants;
import com.longrise.android.byjk.model.DownloadedManageBean;
import com.longrise.android.byjk.model.DownloadedManageDeleteBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.cachecourse.downloadeddetail.DownloadedDetailActivity;
import com.longrise.common.utils.AppUtil;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.ui.dialog.ActionSheetDialog;
import com.longrise.android.upload_offline.DBHelper;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadService;
import com.longrise.filedownloader.OnFileDownloadSuccessListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xkj on 2016/3/11.
 * 显示已经下载的课程的页面
 */
public class DownloadedManageActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        View.OnClickListener, AdapterView.OnItemLongClickListener {

    private static final String TAG = "DownloadedManageActivity";
    private static final int REQ_MANAGE_DETAIL = 10;
    private Context mContext;
    private DBHelper mDBHelper;
    private ListView mLv;
    private DownloadedManageAdapter mAdapter;
    private List<String> mCourseList;

    private RelativeLayout mRlbg;
    private TextView mTv1;


    private DownloadManager mDownloadManager;
    private Toolbar mToolbar;
    private TextView mTvRight;
    private RelativeLayout mRlRight;
    private TextView mTvSd;
    private RelativeLayout mRlSd;
    private Disposable mSdsubscribe;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_downloadedmanage;
    }

    @Override
    public void initView() {
        this.mContext = this;
        mDBHelper = new DBHelper(mContext);
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle(AppUtil.getString(R.string.downloaded_title));
        setSupportActionBar(mToolbar);
        mTvRight = (TextView) findViewById(R.id.iv_toolbar_right_tv);
        mTvRight.setText(AppUtil.getString(R.string.downloaded_qk));
        mRlRight = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl_tv);
        mLv = (ListView) findViewById(R.id.lfview_downloadedmanage_lv);
        mRlbg = (RelativeLayout) findViewById(R.id.lfview_downloadedmanage_rlbg);
        mTv1 = (TextView) findViewById(R.id.lfview_downloadedmanage_tv1);
        mTvSd = (TextView) findViewById(R.id.lfview_downloadedmanage_bottom_tv);
        mRlSd = (RelativeLayout) findViewById(R.id.lfview_downloadedmanage_bottom_rl);
        initData();
        regEvent(true);
        Tracker_Google.getInstance().addGoogleScreenName("下载管理");
    }

    @Override
    protected void onStart() {
        super.onStart();
        getSdRemain();
    }

    private void initData() {
        mDownloadManager = DownloadService.getDownloadManager();
        mAdapter = new DownloadedManageAdapter(mContext);
        mLv.setAdapter(mAdapter);
        getDataFromDB(true);
    }

    private void regEvent(boolean b) {
        mLv.setOnItemClickListener(this);
        mLv.setOnItemLongClickListener(this);
        mRlRight.setOnClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (mDownloadManager != null) {
            mDownloadManager.setOnFileDownloadSuccessListener(new OnFileDownloadSuccessListener() {
                @Override
                public void onSuccess(String url) {
                    getDataFromDB(false);
                }
            });
        }
    }

    /**
     * 从数据库获取已经下载的课程
     */
    public void getDataFromDB(final boolean isShowDialog) {
        Observable.create(new ObservableOnSubscribe<List<DownloadedManageBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DownloadedManageBean>> e) throws Exception {
                e.onNext(getDataFromDBio());
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<DownloadedManageBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxmanager.addDisposable(d);
                        if (isShowDialog) {
                            showLoadingDialog();
                        }
                    }

                    @Override
                    public void onNext(List<DownloadedManageBean> value) {
                        List<DownloadedManageBean> list = value;
                        toShow(list);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });
    }

    /**
     * 从数据库获取数据
     */
    private List getDataFromDBio() {
        ArrayList<DownloadedManageBean> list = null;
        try {
            String userID = UserInfor.getInstance().getUserid();
            list = new ArrayList<>();
            mCourseList = new ArrayList<>();
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery("SELECT * from " + DownloadConstants.TBNAME_DOWNLOAD_COURSE + " where " + DownloadConstants.USERID + " = ? ", new String[]{userID});
            PrintLog.d(TAG, userID);
            while (cursor.moveToNext()) {
                DownloadedManageBean bean = new DownloadedManageBean();
                String courseID = cursor.getString(cursor.getColumnIndex(DownloadConstants.COURSEID));
                bean.setCourseID(courseID);
                bean.setCourseName(cursor.getString(cursor.getColumnIndex(DownloadConstants.COURSENAME)));
                bean.setImagePath(FolderConstants.VIDEO_DIR + UserInfor.getInstance().getUserid() + "/" + courseID + ".jpg");
                String teacherName = cursor.getString(cursor.getColumnIndex(DownloadConstants.TEACHER));
                if (TextUtils.isEmpty(teacherName)) {
                    bean.setTeacher("讲师：保博士");
                } else {
                    bean.setTeacher("讲师：" + teacherName);
                }
                toGetDownLoadNumber(bean, courseID);
                if (Integer.parseInt(bean.getTotalNumber()) > 0) {
                    mCourseList.add(courseID);
                    list.add(bean);  //有选择下载的数据才添加
                } else {
                    toDeletEmptyDB(bean);
                }
            }
            cursor.close();
            db.close();

        } catch (Exception e) {
            PrintLog.d(TAG, "exception:" + e.toString());
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 删除
     */
    private void toDeletEmptyDB(DownloadedManageBean bean) {
        String courseID = bean.getCourseID();
        SQLiteDatabase db = null;
        try {
            db = mDBHelper.getWritableDatabase();
            db.delete(DownloadConstants.TBNAME_DOWNLOAD_COURSE, " userID = ? and courseID = ?",
                    new String[]{UserInfor.getInstance().getUserid(), courseID});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 通过list集合判断显示的状态
     *
     * @param list
     */
    private void toShow(List list) {
        if (list.size() == 0) {
            mRlRight.setVisibility(View.INVISIBLE);
            mRlbg.setVisibility(View.VISIBLE);
            mLv.setVisibility(View.GONE);
            mRlSd.setVisibility(View.VISIBLE);
        } else {
            mLv.setVisibility(View.VISIBLE);
            mRlbg.setVisibility(View.GONE);
            mRlRight.setVisibility(View.VISIBLE);
            mRlSd.setVisibility(View.VISIBLE);
            mAdapter.setData(list);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取当前课程下载和未下载的数量
     */
    public void toGetDownLoadNumber(DownloadedManageBean bean, String courseID) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        float totalLength = 0;
        int totalNum = 0;
        int downloadedNum = 0;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ? and courseID = ? ", new String[]{UserInfor.getInstance().getUserid(), courseID});
            while (cursor.moveToNext()) {
                totalNum++;
                String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
                String cwID = cursor.getString(cursor.getColumnIndex("cwID"));
                File file = new File(cachepath);
                if (file.exists()) {
                    float length = file.length();
                    totalLength = totalLength + length;
                }
                boolean hasDownloaded = FileUtil.isHasDownloaded(mContext, UserInfor.getInstance().getUserid(), cwID);
                PrintLog.d(TAG, "hasDownloaded:" + hasDownloaded);
                if (hasDownloaded) {
                    downloadedNum++;
                }
            }
            bean.setDownloadedSize(totalLength + "");
            bean.setTotalNumber(totalNum + "");
            bean.setDownloadedNumber(downloadedNum + "");
        } catch (Exception e) {
            PrintLog.d(TAG, e.toString());
        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putString(DownloadedDetailActivity.COURSEID, mCourseList.get(position));
        //  Intent intent = new Intent(mContext,DownloadedDetailActivity.class);
        Intent intent = new Intent(mContext, DownloadedDetailLFView.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, REQ_MANAGE_DETAIL);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("删除任务", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                toDeleteCourse(false, mCourseList.get(position));
                            }
                        })
                .setOnCancelListener(new ActionSheetDialog.OncancelListener() {
                    @Override
                    public void onCancel() {

                    }
                }).show();
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_MANAGE_DETAIL) {
            initData();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bb_toolbar_right_rl_tv:  //显示提示全部删除的dialog
                showDeletDialog();
                break;
            case R.id.text_cancle:  //dialog上的取消
                DialogUtil.getInstance().dismiss();
                break;
            case R.id.text_confirm:  //确定清除所有课程
                DialogUtil.getInstance().dismiss();
                toDeleteCourse(true, null);
                break;
        }
    }

    /**
     * 显示删除的dialog
     */
    public void showDeletDialog() {
        View view = View.inflate(mContext, R.layout.dialog_clearcourse, null);
        TextView text_Cancle = (TextView) view.findViewById(R.id.text_cancle);
        TextView text_Confirm = (TextView) view.findViewById(R.id.text_confirm);
        text_Cancle.setOnClickListener(this);
        text_Confirm.setOnClickListener(this);
        DialogUtil.getInstance().creatAlertDialog(mContext, view, 266, 171);
    }

    /**
     * 删除选择的课程 或者 删除全部课程
     */
    private void toDeleteCourse(final boolean isAll, final String courseid) {
        Observable.create(new ObservableOnSubscribe<List<DownloadedManageDeleteBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DownloadedManageDeleteBean>> e) throws Exception {
                if (isAll) {
                    e.onNext(getAllDeleteBeanList());
                } else {
                    e.onNext(getCourseDeleteBeanList(courseid));
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<List<DownloadedManageDeleteBean>, List<DownloadedManageDeleteBean>>() {
                    @Override
                    public List<DownloadedManageDeleteBean>
                    apply(List<DownloadedManageDeleteBean> downloadedManageDeleteBeanlist) throws Exception {
                        List<String> urllist = new ArrayList<String>();
                        for (DownloadedManageDeleteBean bean : downloadedManageDeleteBeanlist) {
                            urllist.add(bean.getDownloadurl());
                        }
                        mDownloadManager.stopAll(urllist);
                        return downloadedManageDeleteBeanlist;
                    }
                })
                .observeOn(Schedulers.io())
                .map(new Function<List<DownloadedManageDeleteBean>, String>() {
                    @Override
                    public String apply(List<DownloadedManageDeleteBean> downloadedManageDeleteBeanlist) throws Exception {
                        toDeleteItem(downloadedManageDeleteBeanlist);
                        return "";
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxmanager.addDisposable(d);
                        showLoadingDialog();
                    }

                    @Override
                    public void onNext(String value) {
                        getDataFromDB(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });
    }

    /**
     * 获取删除单个课程里面的全部已下载的课件
     */
    private List<DownloadedManageDeleteBean> getCourseDeleteBeanList(String courseid) {
        List<DownloadedManageDeleteBean> list = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ? and courseID = ? ", new String[]{UserInfor.getInstance().getUserid(),
                    courseid});
            while (cursor.moveToNext()) {
                DownloadedManageDeleteBean bean = new DownloadedManageDeleteBean();
                String downloadurl = cursor.getString(cursor.getColumnIndex("downloadurl"));
                String cwID = cursor.getString(cursor.getColumnIndex("cwID"));
                String courseID = cursor.getString(cursor.getColumnIndex("courseID"));
                bean.setDownloadurl(downloadurl);
                bean.setCwID(cwID);
                bean.setCourseID(courseID);
                list.add(bean);
            }
        } catch (Exception e) {

        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return list;
    }

    /**
     * 获取已经全部 下载完成的课件
     */
    private List<DownloadedManageDeleteBean> getAllDeleteBeanList() {
        List<DownloadedManageDeleteBean> downloadbeanlist = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL
                    + " where userID = ?", new String[]{UserInfor.getInstance().getUserid()});
            while (cursor.moveToNext()) {
                DownloadedManageDeleteBean bean = new DownloadedManageDeleteBean();
                String downloadurl = cursor.getString(cursor.getColumnIndex("downloadurl"));
                String cwID = cursor.getString(cursor.getColumnIndex("cwID"));
                String courseID = cursor.getString(cursor.getColumnIndex("courseID"));
                bean.setDownloadurl(downloadurl);
                bean.setCwID(cwID);
                bean.setCourseID(courseID);
                downloadbeanlist.add(bean);
            }
        } catch (Exception e) {
            PrintLog.d(TAG, "EXCEPTION:" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return downloadbeanlist;
    }


    /**
     * 分别删除本地文件与数据库数据
     */
    private void toDeleteItem(List<DownloadedManageDeleteBean> list) {
        for (int i = 0; i < list.size(); i++) {
            DownloadedManageDeleteBean downloadedManageDeleteBean = list.get(i);
            String cwID = downloadedManageDeleteBean.getCwID();
            String downloadurl = downloadedManageDeleteBean.getDownloadurl();
            String courseID = downloadedManageDeleteBean.getCourseID();
            toDeleteDB(cwID, courseID);
            toDeleteFile(downloadurl);
        }
    }

    /**
     *
     */
    private synchronized void toDeleteDB(String cwID, String courseID) {
        SQLiteDatabase db = null;
        try {
            db = mDBHelper.getWritableDatabase();
            db.delete(DownloadConstants.TBNAME_DOWNLOAD_DETAIL, " userID = ? and courseID = ? and cwID = ?", new String[]{UserInfor.getInstance().getUserid(), courseID, cwID});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // toDelete();
            if (db != null) {
                db.close();
            }
        }

    }

    /**
     * 获取sd卡的剩余
     * 如果在onStart中订阅，则在onStop中会停止
     */
    private void getSdRemain() {
        mSdsubscribe = Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<Long, String>() {
                    @Override
                    public String apply(Long aLong) throws Exception {
                        File file = Environment.getExternalStorageDirectory();
                        long usableSpace = file.getUsableSpace();
                        String size = Formatter.formatFileSize(mContext, usableSpace);
                        return size;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        mTvSd.setText(AppUtil.getString(R.string.downloaded_sjsy) + s);
                    }
                });
        mRxmanager.addDisposable(mSdsubscribe);
    }

    /**
     * 删除下载的文件
     *
     * @param url 网址
     */
    private void toDeleteFile(String url) {
        mDownloadManager.deleteTask(url);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mRxmanager != null) {
            mRxmanager.removeDisposable(mSdsubscribe);
        }
    }
}
